<?php

namespace app\http\middleware;

use app\common\enum\ScopeEnum;
use app\common\exception\FailException;
use app\common\exception\ForbiddenException;
use Surest\Model\Permission;

class PermissionAuth
{
    public function handle($request, \Closure $next)
    {
        if(!$request->user) {
            throw new FailException(['msg' => '请登录']);
        }

        # 获取当前的请求方法
        # 当数据库中没有添加这个权限的时候, 就放开通行
        // $rule = $request->pathinfo();
        $routeInfo = $request->routeInfo();
        $method = strtolower($request->method());

        # 匹配前 : admin/superstore/online/293
        # 匹配过滤后: admin/superstore/online/<id>
        $rule = $routeInfo['rule'];

        if($request->user->username == 'admin' || $request->user->scope == ScopeEnum::DEVELOPER) {
             return $next($request);
        }
        $where = [];
        $where[] = ['rule', '=', $rule];
        // $where[] = ['method', 'LIKE', '%'.$method.'%'];
        $permission = Permission::where($where)->where('`method` = \'["*"]\' OR `method` LIKE \'%'.$method.'%\'')->find();
        if($permission){
            if(!$request->user->can($permission)) {
                throw new ForbiddenException(['msg' => '没有权限']);
            }
        }else{
            throw new ForbiddenException(['msg' => '没有权限']);
        }

        return $next($request);
    }

    /**
     * 过滤路由
     */
    public function filter_rule($rule)
    {
        // api/v1/permission/update/2
        $pattern = '/(.*)\/([0-9]+)$/';
        $replacement = "$1/<id>";
        return preg_replace($pattern, $replacement, $rule);
    }
}
